<template>
    <h3 class="text-center">付款 报销申请单</h3>
    <el-form class="mt10 forms" ref="ruleFormRef" :model="ruleForm" size="large" status-icon >
        <el-descriptions :column="4" border >
            <el-descriptions-item label="申请人　　　"><div style="width: 200px;"><el-text>{{ user.name }}</el-text></div></el-descriptions-item>
            <el-descriptions-item label="申请部门　　" :span="2"><div style="width: 100%;"><el-text>{{ project.title }}</el-text></div></el-descriptions-item>
            <el-descriptions-item label="申请日期　　"><el-text>{{ ruleForm.apply_date }}</el-text></el-descriptions-item>
            <el-descriptions-item label="申请金额　　"><el-text>{{ ruleForm.apply_price }}</el-text></el-descriptions-item>
            <el-descriptions-item label="稽核金额　　"><el-input v-model="ruleForm.audit_price" /></el-descriptions-item>
            <el-descriptions-item label="还借支　　　"><div style="width: 160px;">{{ruleForm.back_borrow}}</div></el-descriptions-item>
            <el-descriptions-item label="实付金额　　"><el-input v-model="ruleForm.price" /></el-descriptions-item>
            <el-descriptions-item label="对方性质　　">
                <el-select v-model="ruleForm.nature">
                    <el-option label="内部员工报销" value="内部员工报销" />
                    <el-option label="供应商付款" value="供应商付款" />
                    <el-option label="劳务付款" value="劳务付款" />
                    <el-option label="临时工付款" value="临时工付款" />
                    <el-option label="保证金" value="保证金" />
                    <el-option label="其它" value="其它" />
                </el-select>
            </el-descriptions-item>
            <el-descriptions-item label="支付方式　　">
                <el-select v-model="ruleForm.pay_type">
                    <el-option label="对公转账" value="对公转账" />
                    <el-option label="对私转账" value="对私转账" />
                    <el-option label="数字人民币" value="数字人民币" />
                    <el-option label="电子货币" value="电子货币" />
                    <el-option label="现金支票" value="现金支票" />
                    <el-option label="其它" value="其它" />
                </el-select>
            </el-descriptions-item>
            <el-descriptions-item label="支付公司　　">
                <el-select v-model="ruleForm.pay_company">
                    <el-option label="华靖" value="华靖" />
                    <el-option label="华雨" value="华雨" />
                    <el-option label="博创" value="博创" />
                    <el-option label="瑞智腾" value="瑞智腾" />
                </el-select>
            </el-descriptions-item>
            <el-descriptions-item label="银行手续费　"><el-input v-model="ruleForm.bank_charges" /></el-descriptions-item>

            <el-descriptions-item :span="4">
                <h4 class="text-center mt10">收款账号 
                    <el-select v-if="ruleForm.type == 'laborPay' || ruleForm.type == 'materialPay'" @change="onSelectContract" size="default" placeholder="请选择合同" style="width: 200px;">
                        <el-option label="请选择合同" :value="0" />
                        <el-option v-for="item in contractData" :key="item.id" :label="item.b_name" :value="item" />
                    </el-select>
                    <el-select v-if="ruleForm.type == 'reimburse' || ruleForm.type == 'small'" @change="onSelectUser" size="default" placeholder="请选择人员" style="width: 200px;">
                        <el-option label="请选择人员" :value="0" />
                        <el-option v-for="item in userData" :key="item.id" :label="item.name" :value="item" />
                    </el-select>
                </h4>
            </el-descriptions-item>
            <template v-if="ruleForm.type == 'laborPay' || ruleForm.type == 'materialPay'">
                <el-descriptions-item label="账号名称"  :span="2"><el-input v-model="ruleForm.name" /></el-descriptions-item>
                <el-descriptions-item label="开户行　" :span="2"><el-input v-model="ruleForm.bank" /></el-descriptions-item>
                <el-descriptions-item label="账号　　" :span="2"><el-input v-model="ruleForm.bank_number" /></el-descriptions-item>
                <el-descriptions-item label="行号　　" :span="2"><el-input v-model="ruleForm.bank_no" /></el-descriptions-item>
                <el-descriptions-item label="备注　　" :span="4"><el-input v-model="ruleForm.remarks" type="textarea" :autosize="{ minRows: 4 }" /></el-descriptions-item>
            </template>

            <template v-if="ruleForm.type == 'reimburse' || ruleForm.type == 'small'">
                <el-descriptions-item label="账号名称" :span="2"><el-input v-model="ruleForm.name" /></el-descriptions-item>
                <el-descriptions-item label="开户行　" :span="2"><el-input v-model="ruleForm.bank" /></el-descriptions-item>
                <el-descriptions-item label="账号　　" :span="2"><el-input v-model="ruleForm.bank_number" /></el-descriptions-item>
                <el-descriptions-item label="行号　　" :span="2"><el-input v-model="ruleForm.bank_no" /></el-descriptions-item>
                <el-descriptions-item label="备注　　" :span="4"><el-input v-model="ruleForm.remarks" type="textarea" :autosize="{ minRows: 4 }" /></el-descriptions-item>
            </template>
            
        </el-descriptions>
        
        <el-row :gutter="20" class="mt30">
            <el-col :span="12">报销明细：</el-col>
            <el-col :span="12" class="text-right"><el-button size="default" type="primary" @click="onInsert" v-if="tableData.length < 5">添加</el-button></el-col>
        </el-row>
        <el-table :data="tableData" border show-summary :summary-method="getSummaries" :span-method="objectSpanMethod" style="width: 100%;height: 260px !important;" size="small">
            <el-table-column prop="title" label="费用科目" align="center" width="170px" />
            <el-table-column prop="type" label="分摊类型" align="center" width="120px" />
            <el-table-column prop="status" label="项目状态" align="center" width="100px" />
            <el-table-column prop="project" label="费用承担项目" align="center" />
            <el-table-column prop="unit" label="单位" align="center" width="80" />
            <el-table-column prop="nums" label="数量" align="center" width="80" />
            <el-table-column prop="price" label="金额" align="center" width="120" />
            <el-table-column prop="tax_rate" label="税率%" align="center" width="100" />
            <el-table-column prop="tax_price" label="税金" align="center"  width="100" />
            <el-table-column label="发票" width="120" align="center">
                <template #default="scope">
                    <el-text :type="scope.row.invoice ? 'primary' : 'info'"  @click="onShowFile(scope.row.invoice)"> 查看 </el-text>
                </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注" align="center" />
            <el-table-column label="操作" width="100" align="center">
                <template #default="scope">
                    <el-link type="primary" @click="onUpdate(scope.row,scope.$index)">编辑</el-link>
                    <el-link type="danger" @click="onDelete(scope.$index)">删除</el-link>
                </template>
            </el-table-column>
        </el-table>

        <el-row :gutter="20" class="mt30">
            <el-col :span="6">项目部：(实际申请人）</el-col>
            <el-col :span="6">综合管理部</el-col>
            <el-col :span="6">总经理</el-col>
            <el-col :span="6">会计</el-col>
        </el-row>
    </el-form>
    <div class="text-center mt30">
        <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="loading"> 保存 </el-button>
        <el-button type="info" @click="router.go(-1)"> 返回 </el-button>
        <component :is="applyButton" model = "Reimburse" :source = ruleForm.type :price="ruleForm.apply_price" :id = id />
        <component :is="applyRevoke" model = "Reimburse" :source = ruleForm.type :id = id />
        <el-button @click="printElement"> 打印预览 </el-button>
    </div>
    
    <el-dialog v-model="showDetails" title="报销明细" width="30%">
        <el-form ref="DetailsRef" :model="Details" label-width="auto" size="large" status-icon >
            <el-form-item prop="title" label="费用科目">
                <el-select v-model="Details.title" clearable >
                    <el-option label="请选择" :value="0" />
                    <el-option v-for="item in reimburseDetails" :key="item" :label="item" :value="item" />
                </el-select>
            </el-form-item>
            <el-form-item prop="type" label="分摊类型">
                <el-input v-model="Details.type" />
            </el-form-item>
            <el-form-item prop="unit" label="单位">
                <el-input v-model="Details.unit" />
            </el-form-item>
            <el-form-item prop="nums" label="数量">
                <el-input-number style="width: 100%;" v-model="Details.nums"/>
            </el-form-item>
            <el-form-item prop="price" label="金额">
                <el-input-number style="width: 100%;" v-model="Details.price" :precision="2" @change="onChange" />
            </el-form-item>
            <el-form-item prop="tax_rate" label="税率%">
                <el-select v-model="Details.tax_rate" placeholder="请选择" @change="onChange">
                    <el-option label="请选择" value="" />
                    <el-option label="1%" :value="1" />
                    <el-option label="3%" :value="3" />
                    <el-option label="6%" :value="6" />
                    <el-option label="9%" :value="9" />
                    <el-option label="13%" :value="13" />
                </el-select>
            </el-form-item>
            <el-form-item prop="invoice" label="发票">
                <el-button type="primary" @click="onUploadFile('invoice')"> 上传 </el-button>
                <el-button :type="Details.invoice ? 'primary' : 'info'" @click="onShowFile(Details.invoice)"> 查看 </el-button>
            </el-form-item>
            <el-form-item prop="remarks" label="备注">
                <el-input v-model="Details.remarks" type="textarea" />
            </el-form-item>
        </el-form>
        <div class="text-center">
            <el-button type="primary" @click="submitFormDetails(DetailsRef)" :loading="loading"> 保存 </el-button>
        </div>
    </el-dialog>

    <el-dialog v-model="showUpload" title="文件">
        <component :is="uploadMoreFile" :data="uploadData" :fileList="fileList" @saveUpload="saveUpload" />
        <!-- <component :is="uploadMoreImg" :data="uploadData" :fileList="fileList" @saveUpload="saveUpload" /> -->
    </el-dialog>

    <el-dialog v-model="isShowFile" title="文件" class="m0" width="80%" @close="onCloseFile" draggable>
        <component :is="showFileArr" :data="files"/>
    </el-dialog>

    <el-dialog v-model="isPrint" title="打印内容" width="900px">
        <component id="print" :is="reimburseForm" :data = id :type="true" />
    </el-dialog>
</template>
  
<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router';
import http from '../../../util/request';
import { ElMessage, FormInstance } from 'element-plus';
// import uploadFile from '@/components/uploadFile.vue'
import uploadMoreFile from '@/components/uploadMoreFile.vue'
import showFileArr from '@/components/showFileArr.vue'
import applyButton from "@/components/applyButton.vue";
import applyRevoke from "@/components/applyRevoke.vue";
import reimburseForm from '@/components/reimburseForm.vue';
import type { VNode } from 'vue'
import type { TableColumnCtx } from 'element-plus'

let project:any = sessionStorage.getItem('project')
project = JSON.parse(project)
let user:any = sessionStorage.getItem('user')
user = JSON.parse(user)
import func from '../../../util/function';
import router from '../../../router';
const loading = ref<boolean>(false)
const isPrint = ref<boolean>(false)
const reimburseDetails = func.reimburseDetails()
const ruleFormRef = ref<FormInstance>()
const DetailsRef = ref<FormInstance>()

const id:any = ref(useRouter().currentRoute.value.params.id)
const type:any = ref(useRouter().currentRoute.value.params.type)
const showUpload = ref<boolean>(false)
let fileList:any = ref([]);
let uploadData:any = ref({prefix:'reimburse/',type:'',index:0})
const isShowFile = ref<boolean>(false)
const files = ref<string[]>([])
const showDetails = ref<boolean>(false)
const DetailsIndex = ref(-1)
const china_price = ref('')

if(!id.value){
    id.value = 0
}
interface RuleForm {
    id:number
    source_id:number
    type:string
    role_id:number
    user_id:number
    apply_date: string
    apply_price: number
    back_borrow: number
    audit_price: number
    nature: string
    pay_type:string
    price: number
    receive_type: string
    details:any
    pay_company: string
    bank_charges: string
    name: string
    bank: string
    bank_number: string
    bank_no: string
    remarks: string
}

const ruleForm = ref<RuleForm>({
    id:0,
    source_id:0,
    type:'reimburse',
    role_id:0,
    user_id:0,
    apply_date: '',
    price: 0,
    back_borrow: 0,
    audit_price: 0,
    nature: '',
    pay_type:'',
    apply_price: 0,
    receive_type: '',
    details:'',
    pay_company: '',
    bank_charges: '',
    name: '',
    bank: '',
    bank_number: '',
    bank_no: '',
    remarks: '',
})

interface Details {
    id:number
    title:string
    type:string
    project:string
    status:string
    unit:string
    nums:number
    price:number
    audit_price:number
    tax_rate:number
    tax_price:number|string
    invoice:string
    remarks:string
}

const Details = ref<Details>({
    id:0,
    title:'',
    type:'/',
    project:'/',
    status:'/',
    unit:'/',
    nums:0,
    price:0,
    audit_price:0,
    tax_rate:0,
    tax_price:0,
    invoice:'',
    remarks:''
})

const tableData = ref<Details[]>([])
const contractData = ref<any[]>([])
const userData = ref<any[]>([])

const submitForm = async (formEl: FormInstance | undefined) => {
    console.log(ruleForm.value)
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            loading.value = true
            let request:any = null
            ruleForm.value.details = JSON.stringify(tableData.value)
            if(ruleForm.value.id){
                request = http.patch('/reimburse',ruleForm.value)
            }else{
                
                request = http.put('/reimburse',ruleForm.value)
            }
            request.then((response:any)=>{
                loading.value = false
                if(response.data.code != 200){
                    ElMessage.error(response.data.msg);
                    return
                }
                ElMessage.success(response.data.msg);
                id.value = response.data.data.id
                getData()
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const submitFormDetails = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            let d:any = JSON.stringify(Details.value)
            d = JSON.parse(d)
            if(DetailsIndex.value >= 0){
                tableData.value[DetailsIndex.value] = d
                showDetails.value = false
                onApplyPrice()
                return
            }
            tableData.value.push(d)
            onApplyPrice()
            showDetails.value = false
        } else {
            console.log('error submit!', fields)
        }
    })
}

const onChange = () => {
    // 税额 = 金额 / (1 + 税率) * 税率
    Details.value.tax_price = (Details.value.price / (1 + (Details.value.tax_rate/100)) * Details.value.tax_rate/100).toFixed(2)
}

// columns: TableColumnCtx<T>[]
interface SummaryMethodProps<T = Details> {
  columns: TableColumnCtx[]
  data: T[]
}

const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const sums: (string | VNode)[] = []
  columns.forEach((column, index) => {
    const values = data.map((item:any) => Number(item[column.property]))
    sums[index] = `${values.reduce((prev:any, curr:any) => {
        if(index == 0){
            return '合计'
        }
        if(index == 1){
            return '大写金额'
        }
        if(index == 3){
            return china_price.value
        }
        if(index == 8){
            return parseFloat(prev + curr)
        }
        if(index == 6){
            return ruleForm.value.apply_price.toFixed(2)
        }

        return ''
    }, 0)}`
  })
  return sums
}

// 合并单元格方法
const objectSpanMethod = ({ rowIndex, columnIndex }: any) => {
  // 只处理合计行（最后一行）
  if (rowIndex === tableData.value.length) {
    if (columnIndex === 2) {
      return {
        rowspan: 1,
        colspan: 3
      };
    }
  }
};

const onApplyPrice = () => {
    let apply_price:number = 0;
    tableData.value.forEach((e:any) => {
        apply_price += parseFloat(e.price)
    });
    ruleForm.value.apply_price = apply_price
    china_price.value = func.numberToChinese(ruleForm.value.apply_price)
}

const onInsert = () => {
    Details.value.id = 0
    Details.value.title = '',
    Details.value.type = '/',
    Details.value.project = project.title,
    Details.value.status = project.status,
    Details.value.remarks = '/',
    Details.value.nums = 0,
    Details.value.price = 0,
    Details.value.audit_price = 0,
    Details.value.tax_rate = 0,
    Details.value.tax_price = 0,
    Details.value.invoice = '',
    DetailsIndex.value = -1
    showDetails.value = true
    
}

const onUpdate = (data:any,index:number) => {
    data.price = parseInt(data.price)
    Details.value = data
    DetailsIndex.value = index
    showDetails.value = true
}

const onDelete = (index:number) => {
    tableData.value.splice(index,1)
    onApplyPrice()
}

const getData = () => {
    ruleForm.value.apply_date = new Intl.DateTimeFormat('zh-CN').format(new Date()).replace(/\//g, '-');
    if(id.value == 0){
        return;
    }
    http.get('/reimburse/'+id.value).then((response:any)=>{
        ruleForm.value = response.data.data
        tableData.value = ruleForm.value.details
        ruleForm.value.details = ''
        onApplyPrice()
    })
}


const onSelectUser = (data:any) => {
    ruleForm.value.name = data.name
    ruleForm.value.bank = data.bank
    ruleForm.value.bank_number = data.bank_account
    ruleForm.value.bank_no = data.bank_number
    ruleForm.value.source_id = data.id
}

const onSelectContract = (data:any) => {
    ruleForm.value.name = data.b_name
    ruleForm.value.bank = data.b_bank
    ruleForm.value.bank_number = data.b_bank_account
    ruleForm.value.bank_no = data.b_bank_number
    ruleForm.value.source_id = data.id
}

const onGetContract = () => {
    let url = '/material/contract'
    if(ruleForm.value.type == 'laborPay'){
        url = '/labor/contract'
    }
    http.post(url,{}).then((response:any)=>{
        contractData.value = response.data.data
        if(ruleForm.value.type == 'laborPay'){
            contractData.value.forEach((e:any) => {
                if(e.b_name == '' || e.b_name == '/'){
                    e.b_name = e.u_name
                }
            });
        }
    })
}

const onGetUser = () => {
    http.post('user/all',{}).then((response:any)=>{
        userData.value = response.data.data
    })
}

const onUser = () => {
    http.post('user/imprest',{}).then((response:any)=>{
        user = response.data.data
        ruleForm.value.back_borrow = user.imprest_price_sum
    })
}

const printElement = () => {
    isPrint.value = true
}

onMounted(()=>{
    ruleForm.value.type = type
    getData()
    onGetContract()
    onGetUser()
    onUser()
})


const onUploadFile = (type:string) => {
    uploadData.value.type = type
    if(type == 'invoice'){
        uploadData.value.image = Details.value.invoice
    }
    uploadData.value.id = id.value
    fileList.value = []
    uploadData.value.file = Details.value.invoice
    if(Details.value.invoice){
        let f:any = Details.value.invoice.split(',')
        f.forEach((e:any) => {
            fileList.value.push({name:e,url:e})
        });
    }
    showUpload.value = true
}

const saveUpload = (data:string[]) => {
    if(uploadData.value.type == 'invoice'){
        Details.value.invoice = data.join(',');
    }
    showUpload.value = false
}

const onShowFile = (file:string) => {
    if(!file){
        ElMessage.error('未上传文件');return
    }
    files.value = file.split(',')
    isShowFile.value = true
}

const onCloseFile = () => {
    files.value = []
}
</script>
<style scoped>
.forms{height: calc(100vh - 30vh);overflow-y: scroll;padding: 15px;}
</style>
